package com.ysd.lis.service.bak.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.aspect.SysEventLog;
import com.ysd.lis.entity.*;
import com.ysd.lis.entity.bak.LabReqMainBak;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.bak.LabReqMainBakMapper;
import com.ysd.lis.mapper.lab.LabMaininfoMapper;
import com.ysd.lis.mapper.lab.LabReqMainMapper;
import com.ysd.lis.mapper.lab.LabReqMainQueryMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.mapper.sys.SysOrgDepartmentMapper;
import com.ysd.lis.request.*;
import com.ysd.lis.request.RptResultDto;
import com.ysd.lis.request.lab.LabMaininfoCreateOrUpdateDto;
import com.ysd.lis.request.lab.LabReqMainDto;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.bak.LabReqMainBakService;
import com.ysd.lis.service.lab.*;
import com.ysd.lis.service.lab.impl.LabMainInfoServiceBakImpl;
import com.ysd.lis.service.lab.impl.LabMaininfoServiceImpl;
import com.ysd.lis.util.InterfaceUtil;
import com.ysd.util.PinYinUtil;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 检验申请主表 服务实现类
 * </p>
 *
 * @author WH
 * @since 2024-11-26
 */
@Service
public class LabReqMainBakServiceImpl extends ServiceImpl<LabReqMainBakMapper, LabReqMainBak> implements LabReqMainBakService {
    private static final Logger logger = LoggerFactory.getLogger(LabMaininfoServiceImpl.class);

    @Autowired
    private LabReqMainBakMapper labReqMainBakMapper;

    @Autowired
    SysOrgDepartmentMapper sysOrgDepartmentMapper;

    @Autowired
    LabReqMainMapper labReqMainMapper;

    @Autowired
    LabMainInfoServiceBakImpl labMainInfoServiceBak;

    @Autowired
    SysParamValueService sysParamValueService;

    @Autowired
    LabMaininfoMapper labMaininfoMapper;

    @Autowired
    SysInterfaceMapper sysInterfaceMapper;

    @Autowired
    LabReqMainService labReqMainService;

    @Autowired
    LabMaininfoService labMaininfoService;

    @Autowired
    LabTemplateService labTemplateService;

    @Autowired
    LabRptresultService labRptresultService;

    @Autowired
    LabMainStateService labMainStateService;
    @Autowired
    private InterfaceUtil interfaceUtil;

    @Autowired
    LabReqStateService labReqStateService;

    @Autowired
    private LabReqMainQueryMapper labReqMainQueryMapper;

    @Autowired
    SysBasDictDetailService sysBasDictDetailService;

    @Override
    public Result findHisStoryLabReqMainPageList(LabMaininfoPageDto maininfoPageDto) {
        LambdaQueryWrapper<LabReqMainBak> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabReqMainBak::getDelFlag, 0);
        Timestamp startTime = Timestamp.valueOf(maininfoPageDto.getSampledaBegin());
        Timestamp endTime = Timestamp.valueOf(maininfoPageDto.getSampledaEnd());
        // 申请时间
        lambdaQueryWrapper.ge(LabReqMainBak::getReqTime, startTime);
        lambdaQueryWrapper.le(LabReqMainBak::getReqTime, endTime);
        if (StringUtils.isNotBlank(maininfoPageDto.getReqNoS()) && StringUtils.isNotBlank(maininfoPageDto.getReqNoE())) {
            lambdaQueryWrapper.ge(LabReqMainBak::getReqNo, maininfoPageDto.getReqNoS());
            lambdaQueryWrapper.le(LabReqMainBak::getReqNo, maininfoPageDto.getReqNoE());
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqNo()), LabReqMainBak::getReqNo, maininfoPageDto.getReqNo());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getPatNo()), LabReqMainBak::getPatNo, maininfoPageDto.getPatNo());
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(maininfoPageDto.getPatNa())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabReqMainBak::getPatNa, maininfoPageDto.getPatNa()).or().like(LabReqMainBak::getPatPyName, maininfoPageDto.getPatNa()));
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getBedNo()), LabReqMainBak::getBedNo, maininfoPageDto.getBedNo());
        if (StringUtils.isNotBlank(maininfoPageDto.getSamplingTime())) {
            Timestamp samplingStart = Timestamp.valueOf(maininfoPageDto.getSamplingTime() + " 00:00:00");
            Timestamp samplingEnd = Timestamp.valueOf(maininfoPageDto.getSamplingTime() + " 23:59:59");
            lambdaQueryWrapper.ge(LabReqMainBak::getSamplingTime, samplingStart);
            lambdaQueryWrapper.le(LabReqMainBak::getSamplingTime, samplingEnd);
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getFeeType()), LabReqMainBak::getFeeType, maininfoPageDto.getFeeType());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqDept()), LabReqMainBak::getReqDept, maininfoPageDto.getReqDept());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getPatType()), LabReqMainBak::getPatType, maininfoPageDto.getPatType());

        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getSex()), LabReqMainBak::getSex, maininfoPageDto.getSex());

        // 过滤无条码
        if (maininfoPageDto.getIsFilterNoSpecCode()) {
            lambdaQueryWrapper.isNotNull(LabReqMainBak::getReqNo);
        }
        List<LabReqMainBak> labReqMainPage = labReqMainBakMapper.selectList(lambdaQueryWrapper);

        LambdaQueryWrapper<SysOrgDepartment> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(SysOrgDepartment::getDelFlag, 0);
        List<SysOrgDepartment> sysOrgDepartments = sysOrgDepartmentMapper.selectList(lambdaQueryWrapper1);

        labReqMainPage.forEach(a -> {
            if (StringUtils.isNotEmpty(a.getReqDept())) {
                Optional<SysOrgDepartment> first = sysOrgDepartments.stream().filter(s -> StringUtils.isNotBlank(s.getCode())).filter(s -> s.getCode().equals(a.getReqDept())).findFirst();
                if (first.isPresent()) {
                    a.setReqDeptNa(first.get().getName());
                }
            }
        });
        List<LabReqMainBak> returnList = new ArrayList<>();
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(labReqMainPage)) {
            if (StringUtils.isNotEmpty(maininfoPageDto.getFeeName())) {
                Set<String> set = new HashSet<>();
                List<String> list = Arrays.asList(maininfoPageDto.getFeeName().split(","));
                for (String a : list) {
                    List<LabReqMainBak> collect = labReqMainPage.stream().filter(p -> StringUtils.isNotEmpty(p.getReqPurpose()) && p.getReqPurpose().contains(a)).collect(Collectors.toList());
                    returnList.addAll(collect);
                }
                ;
            } else {
                returnList = labReqMainPage;
            }
        }
        returnList = returnList.stream().distinct().collect(Collectors.toList());
        return Result.succ(1, "查询成功", returnList);
    }


    // 标本扫码上机(获取信息) V2版本先扫码
    @Override
    public Result insertMaininfoByReqNo(AddLabMaininfo labReqMain) throws JsonProcessingException {
        String reqno = labReqMain.getReqNo();
        long l = System.currentTimeMillis();

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        String orgId = RedisUserManager.getStoreOrg("currentOrg" + token);

        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();

        queryWrapper.selectAll(LabReqMain.class)
                .selectAs(LabSampleType::getSampleTypeName, LabReqMain::getSampleTypeNa)
                .leftJoin(LabSampleType.class, LabSampleType::getSampleTypeCode, LabReqMain::getSampleType)
                .eq(LabReqMain::getDelFlag, 0)
                .eq(LabReqMain::getReqNo, reqno)
                .orderByDesc(LabReqMain::getCreateTime);

        List<LabReqMain> reqMains = labReqMainMapper.selectList(queryWrapper);
        LabReqMain reqMain = reqMains.isEmpty() ? null : reqMains.get(0);
        if (reqMain == null && StringUtils.isNotBlank(reqno)) {
            try {
                // 从接口中获取数据
                Result rsult = labMainInfoServiceBak.getApiReqMainInfo(labReqMain);
                if ("400".equals(rsult.getStatus().get("code") + "")) {
                    throw new RuntimeException(rsult.getStatus().get("msg") + "");
                }
            } catch (Exception e) {
                throw e;
            }

            reqMain = labMainInfoServiceBak.getLabReqMainEntity(reqno);// labReqMainMapper.selectOne(queryWrapper);
            if (reqMain == null) {
                throw new RuntimeException("未获取到申请信息！");
            }
        }

        /*验证系统参数，无条码号，禁止创建上机记录 2025-04-15 青岛优抚 王超提出需求，彭大jb分派*/
        SysParamParam sysp1111 = new SysParamParam();
        sysp1111.setParamCode("xtxxcs");
        sysp1111.setField("wtmhjzcjsjjl");
        List<SysParamFieldValueDto> r111 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1111);
        if (!r111.isEmpty()) {
            if ("1".equals(r111.get(0).getValue()) && StringUtils.isBlank(reqno)) {
                return Result.fail("无条码号禁止创建上机记录");
            }
        }

        /*验证系统参数，东北双塔取消上机退费后2025-03-20，禁止上机*/
        SysParamParam sysp0 = new SysParamParam();
        sysp0.setParamCode("xtxxcs");
        sysp0.setField("qxsjreturnfeenocheck");
        List<SysParamFieldValueDto> r0 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp0);
        if (!r0.isEmpty()) {
            if ("1".equals(r0.get(0).getValue()) && "1".equals(reqMain.getIsCancel() + "")) {
                return Result.fail("已取消上机退费，无法再次上机");
            }
        }

        // TODO 判断当前申请的状态，如果已经作废的不允许上机
        if (!BeanUtil.isEmpty(reqMain)) {
            try {
                if (!BeanUtil.isEmpty(reqMain.getIsCancel()) && reqMain.getIsCancel().equals(1)) {
                    return Result.fail("当前标本已经作废," + reqMain.getCancelReason());
                }
            } catch (Exception ex) {
                // TODO
            }

            /*验证系统参数，无签收时间，禁止上机*/
            SysParamParam sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("wqssjbbjzsj");
            List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                if ("1".equals(r1.get(0).getValue()) && BeanUtil.isEmpty(reqMain.getSignTime())) {
                    return Result.fail("无签收时间标本禁止上机");
                }
            }

            // 住院无签收时间标本禁止上机
            /*验证系统参数，无签收时间，禁止上机*/
            sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("zywqssjbbjzsj");
            r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                if ("1".equals(r1.get(0).getValue()) && BeanUtil.isEmpty(reqMain.getSignTime()) && !BeanUtil.isEmpty(reqMain.getPatType()) && reqMain.getPatType().equals("3")) {
                    return Result.fail("住院无签收时间标本禁止上机");
                }
            }

            /*验证系统参数，无采样时间,禁止上机*/
            sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("wcysjjzsj");
            r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                String value = r1.get(0).getValue();
                if (ToolsUtils.isNotEmpty(value)) {
                    List<String> listValue = getListValueMethod(value);
                    if (ToolsUtils.isNotEmpty(reqMain.getPatType()) && listValue.contains(reqMain.getPatType()) && ToolsUtils.isEmpty(reqMain.getSamplingTime())) {
                        return Result.fail("无采样时间禁止上机");
                    }
                }
            }

            /*验证系统参数，无采样人,禁止上机*/
            sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("wcyrjzsj");
            r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                String value = r1.get(0).getValue();
                if (ToolsUtils.isNotEmpty(value)) {
                    List<String> listValue = getListValueMethod(value);
                    if (ToolsUtils.isNotEmpty(reqMain.getPatType()) && listValue.contains(reqMain.getPatType()) && ToolsUtils.isEmpty(reqMain.getSamplingDoctor())) {
                        return Result.fail("无采样人禁止上机");
                    }
                }
            }

            //---报告单元
            /*验证系统参数，无采样时间,禁止上机*/
            sysp1 = new SysParamParam();
            sysp1.setParamCode("bgdyxtcs");
            sysp1.setField("bgdywcysjjzsj");
            sysp1.setClassifyCode(labReqMain.getRptGroup());

            r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                String value = r1.get(0).getValue();
                if (ToolsUtils.isNotEmpty(value)) {
                    List<String> listValue = getListValueMethod(value);
                    if (ToolsUtils.isNotEmpty(reqMain.getPatType()) && listValue.contains(reqMain.getPatType()) && ToolsUtils.isEmpty(reqMain.getSamplingTime())) {
                        return Result.fail("无采样时间禁止上机");
                    }
                }
            }
            //---报告单元
            /*验证系统参数，无采样人,禁止上机*/
            sysp1 = new SysParamParam();
            sysp1.setParamCode("bgdyxtcs");
            sysp1.setField("bgdywcyrjzsj");
            sysp1.setClassifyCode(labReqMain.getRptGroup());
            r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                String value = r1.get(0).getValue();
                if (ToolsUtils.isNotEmpty(value)) {
                    List<String> listValue = getListValueMethod(value);
                    if (ToolsUtils.isNotEmpty(reqMain.getPatType()) && listValue.contains(reqMain.getPatType()) && ToolsUtils.isEmpty(reqMain.getSamplingDoctor())) {
                        return Result.fail("无采样人禁止上机");
                    }
                }
            }
        }


        LambdaQueryWrapper<LabMaininfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!BeanUtil.isEmpty(labReqMain.getReqNo())) {
            lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0).eq(LabMaininfo::getReqNo, labReqMain.getReqNo()).eq(LabMaininfo::getRptGroup, labReqMain.getRptGroup()).eq(LabMaininfo::getSampleda, labReqMain.getSampleda()).eq(LabMaininfo::getSampleNo, labReqMain.getSampleNo());
        } else {
            lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0).eq(LabMaininfo::getRptGroup, labReqMain.getRptGroup()).eq(LabMaininfo::getSampleda, labReqMain.getSampleda()).eq(LabMaininfo::getSampleNo, labReqMain.getSampleNo());
        }

        // 检查标本号重复上机
        List<LabMaininfo> labMainInfoList = labMaininfoMapper.selectList(lambdaQueryWrapper);
        /*条码号为空*/
        if (!labMainInfoList.isEmpty()) {
            /*同意报告单元  检验日期 不能有重复标本号*/
            if (BeanUtil.isEmpty(labReqMain.getReqNo())) {
                return Result.fail("同一天，同一报告单元，标本号不允许重复!");
            }
        }

        // TODO 条码号重复上机，根据系统选项判断是否允许上机还是提示
        try {
            SysParamParam kcflrdstndtm = new SysParamParam();
            /*可重复录入多少天内的条码 kcflrdstndtm*/
            kcflrdstndtm = new SysParamParam();
            kcflrdstndtm.setParamCode("bgdyxtcs");
            kcflrdstndtm.setField("kcflrdstndtm");
            kcflrdstndtm.setClassifyCode(labReqMain.getRptGroup());
            List<SysParamFieldValueDto> kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(kcflrdstndtm);
            String kcflrdstndtmStr = kcflrdstndtmLst.get(0).getValue();

            /*扫码时不提示重复使用 smsbtscfsy*/
            kcflrdstndtm = new SysParamParam();
            kcflrdstndtm.setParamCode("bgdyxtcs");
            kcflrdstndtm.setField("smsbtscfsy");
            kcflrdstndtm.setClassifyCode(labReqMain.getRptGroup());
            List<SysParamFieldValueDto> smsbtscfsy = sysParamValueService.findSysParamFieldAndValueListByCode(kcflrdstndtm);
            String smsbtscfsyStr = smsbtscfsy.get(0).getValue();

            if (!BeanUtil.isEmpty(reqno)) {
                lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
                lambdaQueryWrapper.eq(LabMaininfo::getReqNo, reqno);

                // 检查标本号重复上机
                labMainInfoList = labMaininfoMapper.selectList(lambdaQueryWrapper);
                if (!BeanUtil.isEmpty(kcflrdstndtmStr) && kcflrdstndtmStr.equals("2") && !labMainInfoList.isEmpty()) {
                    return Result.fail("条码号已上机，禁止重复上机");
                }

                lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
                lambdaQueryWrapper.eq(LabMaininfo::getReqNo, reqno);
                lambdaQueryWrapper.eq(LabMaininfo::getRptGroup, labReqMain.getRptGroup());
                labMainInfoList = labMaininfoMapper.selectList(lambdaQueryWrapper);
                if (!BeanUtil.isEmpty(kcflrdstndtmStr) && kcflrdstndtmStr.equals("3") && !labMainInfoList.isEmpty()) {
                    return Result.fail("该报告单元内本条码号已上机，禁止重复上机");
                }
            }
        } catch (Exception e) {
            // ToDo
        }

        int configSpecScheduleDays = 30;


        try {
            /*扫码上机时允许的检验日期天数 smsjsyxdjyrqts*/
            SysParamParam smsjsyxdjyrqts = new SysParamParam();
            smsjsyxdjyrqts.setParamCode("bgdyxtcs");
            smsjsyxdjyrqts.setField("smsjsyxdjyrqts");
            smsjsyxdjyrqts.setClassifyCode(labReqMain.getRptGroup());
            List<SysParamFieldValueDto> smsjsyxdjyrqtsLst = sysParamValueService.findSysParamFieldAndValueListByCode(smsjsyxdjyrqts);
            String smsjsyxdjyrqtsStr = smsjsyxdjyrqtsLst.get(0).getValue();
            configSpecScheduleDays = Integer.parseInt(smsjsyxdjyrqtsStr);
        } catch (Exception e) {
            configSpecScheduleDays = 30;
        }

        SysUser sysUser = RedisUserManager.getUser();
        // 扫码上机时允许的检验日期天数
        Date now = new Date();
        Timestamp sampleda = labReqMain.getSampleda();

        Date date = timeToDate(sampleda);

        int days = differentDaysByMillisecond(date, now);
        if (days > configSpecScheduleDays) {
            return Result.fail("检验日期超出设定值" + days + "天，禁止上机!");
        }

        // 扫码上机从lab_reqmain里取数据存入上机表中
        LabMaininfo labMaininfo = new LabMaininfo();
        if (!BeanUtil.isEmpty(labReqMain.getTestDoctor())) {
            labMaininfo.setTestDoctor(labReqMain.getTestDoctor());
        } else {
            labMaininfo.setTestDoctor(sysUser.getUsername());
        }

        /*上机时自动补充签收时间*/
        SysParamParam sysp1 = new SysParamParam();
        sysp1 = new SysParamParam();
        sysp1.setParamCode("xtxxcs");
        sysp1.setField("sjszdbcqssj");
        List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
        if (!r1.isEmpty()) {
            if ("1".equals(r1.get(0).getValue()) && BeanUtil.isEmpty(labMaininfo.getSignTime())) {
                labMaininfo.setSignerDoctor(sysUser.getUsername());
                labMaininfo.setSignTime(new Timestamp(System.currentTimeMillis()));
            }
        }
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, orgId);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        if (!BeanUtil.isEmpty(reqMain)) {
            if (!r1.isEmpty()) {
                logger.info("开始执行扫码上机签收更新医嘱状态接口");
                /*上机时自动补充申请签收时间*/
                if (r1.get(0).getValue().equals("1") && BeanUtil.isEmpty(reqMain.getSignTime())) {
                    logger.info("开始执行扫码上机签收更新医嘱状态接口22222222222222");
                    reqMain.setSignerDoctor(sysUser.getUsername());
                    reqMain.setSignTime(new Timestamp(System.currentTimeMillis()));
                    reqMain.setSignerNa(sysUser.getRealname());
                    reqMain.setIsSign(new BigDecimal(1));
                    labReqMainService.updateById(reqMain);
                    // 开始上机医嘱状态更
                    if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
                        /*发布报告相关*/
                        for (String webUrl : collect) {
                            // 调用修改状态接口
                            String updateUrl = webUrl + "/public/updateReportStatus";
                            Map<String, Object> updateMap = new HashMap<>();
                            updateMap.put("status", "0304");//签收
                            updateMap.put("reqNo", reqMain.getReqNo());
                            updateMap.put("username", sysUser.getUsername());
                            updateMap.put("realname", sysUser.getRealname());
                            updateMap.put("patType", reqMain.getPatType());
                            logger.info("开始执行扫码上机签收更新医嘱状态接口入参为:" + JSONUtil.toJsonStr(updateMap));
                            HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                            if ("3".equals(reqMain.getPatType())) {
                                String updateUrlHl7 = webUrl + "/public/sampleReceive";
                                HttpUtil.createPost(updateUrlHl7).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                            }
                        }
                    }
                }
            }
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
                /*发布报告相关*/
                for (String webUrl : collect) {
                    //添加系统参数判断是否需要重新获取计费信息，（东北双塔天健接口需求）2025-03-18
                    /*添加系统参数判断是否需要重新获取计费信息*/
                    SysParamParam sysp111 = new SysParamParam();
                    sysp111.setParamCode("xtxxcs");
                    sysp111.setField("smsjsfxycxlqsq");
                    List<SysParamFieldValueDto> xtcs1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp111);
                    if (!xtcs1.isEmpty()) {
                        if ("1".equals(xtcs1.get(0).getValue())) {
                            Map<String, Object> updateMap = new HashMap<>();
                            updateMap.put("status", "0304");
                            updateMap.put("reqNo", reqMain.getReqNo());
                            updateMap.put("username", sysUser.getUsername());
                            updateMap.put("realname", sysUser.getRealname());
                            updateMap.put("patType", reqMain.getPatType());
                            updateMap.put("orgId", sysUser.getOrgId());
                            logger.info("开始执行上机计费接口:" + JSONUtil.toJsonStr(updateMap));
                            String addFeeUrl = webUrl + "/public/beginCheckAddFee";
                            String body = HttpUtil.createPost(addFeeUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                            JSONObject jsonObject = new JSONObject(body);
                            JSONObject status = jsonObject.getJSONObject("status");
                            String code = status.get("code").toString();
                            if ("400".equals(code)) {
                                return Result.fail(jsonObject.getStr("data"));
                            }
                        }
                    }
                }
            }
            /*检验医师为空时取当前登录人（前端）*/
            sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("jyyswkqdqdlr");
            r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                if ("1".equals(r1.get(0).getValue()) && BeanUtil.isEmpty(labReqMain.getTestDoctor())) {
                    labMaininfo.setTestDoctor(sysUser.getUsername());
                }
            }
        }

        if (reqMain != null) {
            BeanUtil.copyProperties(reqMain, labMaininfo, "id", "isPrint", "printTime", "printDoctor", "creator", "editor", "createTime", "editTime", "delFlag");
        } else {
            labMaininfo.setRptGroup(labReqMain.getRptGroup());
            labMaininfo.setSampleda(labReqMain.getSampleda());
            labMaininfo.setSampleNo(labReqMain.getSampleNo());
        }
        labMaininfo.setTestTime(new Timestamp(System.currentTimeMillis()));

        if (StringUtils.isNotBlank(labMaininfo.getPatNa())) {
            String apply = PinYinUtil.firstPinYinFun.apply(labMaininfo.getPatNa());
            labMaininfo.setPatPyName(apply);
        }

        if (reqMain != null) {
            labMaininfo.setRemark1(reqMain.getRemark1());
            labMaininfo.setRemark2(reqMain.getRemark2());
            labMaininfo.setRemark3(reqMain.getRemark3());
            labMaininfo.setRemark4(reqMain.getRemark4());
            labMaininfo.setRptGroup(labReqMain.getRptGroup());
            labMaininfo.setSampleNo(labReqMain.getSampleNo());
            labMaininfo.setSampleda(labReqMain.getSampleda());
            labMaininfo.setOrgId(sysUser.getOrgId());
            labMaininfo.setIsChk(new BigDecimal(0));
        }
        if (StringUtils.isNotBlank(labReqMain.getChkDoctor())) {
            labMaininfo.setChkDoctor(labReqMain.getChkDoctor());
        }

        if (labMaininfo.getSampleType() == null) {
            // 如果标本类型是空的，设置默认类型
            // TODO
        }

        /*微生物扫码上机，计算方案、选用的培养基*/
        if (BeanUtil.isNotEmpty(labReqMain) && StringUtils.isNotBlank(labReqMain.getDataType()) && "2".equals(labReqMain.getDataType())) {
            if (ToolsUtils.isNotEmpty(reqMain) && StringUtils.isBlank(reqMain.getPurposeNo())) {
                labReqMainService.bacCalcPurposeByScanReqNo(reqMain, labMaininfo);
            } else if (ToolsUtils.isNotEmpty(reqMain) && StringUtils.isNotBlank(reqMain.getPurposeNo())) {
                // 已走签收
                labReqMainService.bacTestUpdateWorkFlowV1(reqMain, labMaininfo);
            } else if (ToolsUtils.isEmpty(reqMain)) {
                // 无申请，默认细菌检验
                labReqMainService.bacTestUseDefaultWorkFlowWithPurpose(reqMain, labMaininfo);
            } else {
                labReqMainService.bacTestUseDefaultWorkFlowWithPurpose(reqMain, labMaininfo);
            }
        }

        /*微生物扫码上机，采用默认方案、无培养基*/

        if (!"4".equals(labMaininfo.getPatType())) {
            try {
                if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
                    for (String webUrl : collect) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.set("id", labMaininfo.getId());
                        jsonObject.set("orgId", sysUser.getOrgId());
                        jsonObject.set("reqNo", labMaininfo.getReqNo());
                        jsonObject.set("username", sysUser.getUsername());
                        jsonObject.set("realname", sysUser.getRealname());
                        String body = HttpUtil.createPost(webUrl + "/lisRestFul/noticeHisFee").body(JSONUtil.toJsonStr(jsonObject)).contentType("application/json").execute().body();
                        logger.info(body);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        // 插入模板数据
        TemplateParams tmpParam = new TemplateParams();
        tmpParam.setMaininfoId(labMaininfo.getId());
        tmpParam.setRptGroup(labMaininfo.getRptGroup());
        tmpParam.setSampleda(labMaininfo.getSampleda());
        tmpParam.setSampleNo(labMaininfo.getSampleNo());
        tmpParam.setReqNo(reqno);
        List<LabRptresult> rptresultList = labTemplateService.batchDefItemDictAndTemplate(tmpParam);

        if (rptresultList != null) {
            labMaininfo.setResultList(rptresultList);
        }


        //开始上机医嘱状态更新
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect) && ToolsUtils.isNotEmpty(reqMain)) {
            /*发布报告相关*/
            for (String webUrl : collect) {
                //调用修改状态接口
                String updateUrl = webUrl + "/public/updateReportStatus";
                Map<String, Object> updateMap = new HashMap<>();
                updateMap.put("status", "0305");//上机
                updateMap.put("reqNo", reqMain.getReqNo());
                updateMap.put("username", sysUser.getUsername());
                updateMap.put("realname", sysUser.getRealname());
                updateMap.put("orgId", sysUser.getOrgId());
                updateMap.put("patType", reqMain.getPatType());
                updateMap.put("chargeType", "1");
                logger.info("开始上机更新医嘱状态入参为:" + JSONUtil.toJsonStr(updateMap));
                HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                //调用执行医嘱确费接口
                if ("3".equals(reqMain.getPatType())) {
                    String yzqfUrl = webUrl + "/yzqf";
                    HttpUtil.createPost(yzqfUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                }
            }
        }
        //调用开始上机接口
        try {
            String code = "BEGIN_CHECK";
            List<SysInterfaceDict> allSysInterfaceDict = interfaceUtil.getAllSysInterfaceDict(code);
            if (CollectionUtils.isNotEmpty(allSysInterfaceDict) && ToolsUtils.isNotEmpty(reqMain)) {
                for (SysInterfaceDict sysInterfaceDict : allSysInterfaceDict) {
                    try {
                        String webUrl = "";
                        if (sysInterfaceDict.getWebUrl().startsWith("http:")) {
                            webUrl = sysInterfaceDict.getWebUrl() + "/" + sysInterfaceDict.getCode();
                        } else {
                            webUrl = "http://" + sysInterfaceDict.getWebUrl() + "/" + sysInterfaceDict.getCode();
                        }
                        JSONObject q = new JSONObject();
                        q.set("reqNo", reqno);
                        q.set("username", sysUser.getUsername());
                        q.set("realname", sysUser.getRealname());
                        String returnMsg1 = HttpUtil.createPost(webUrl).body(JSONUtil.toJsonStr(q)).contentType("application/json").execute().body();
                    } catch (Exception e) {
                        logger.info("接口方法异常：" + sysInterfaceDict.getType());
                    }
                }
            }
        } catch (Exception e) {
            logger.info("开始上机接口异常，请核实！");
            e.printStackTrace();
        }
        return Result.succ(1, "扫码上机成功", labMaininfo);
        // return Result.succ(1, "扫码上机成功", labMainInfoServiceBak.getMainInfoById(labMaininfo.getId()));
        // } else {
        //     return Result.fail("扫码上机失败！");
        // }
    }


    //,LabMaininfo labMaininfo,AddLabMaininfo labReqMain, LabReqMain reqMain, List<String> collect
    // 标本扫码上机(保存信息)
    @Override
    public Result insertMaininfo(LabMaininfo labMaininfo) throws JsonProcessingException {
        // AddLabMaininfo labReqMain = labMaininfoList.getAddLabMaininfo();
        // LabMaininfo labMaininfo = labMaininfoList.getLabMaininfo();

        String reqno = labMaininfo.getReqNo();
        SysUser sysUser = RedisUserManager.getUser();

        if(StringUtils.isNotEmpty(reqno)) {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            String token = request.getHeader("Authorization").replace("Bearer ", "");
            String orgId = RedisUserManager.getStoreOrg("currentOrg" + token);


            LambdaQueryWrapper<LabReqMain> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LabReqMain::getReqNo, reqno).eq(LabReqMain::getDelFlag, 0);
            LabReqMain reqMain = labReqMainMapper.selectOne(queryWrapper);

            LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysInterface::getDelFlag, 0);
            wrapper.eq(SysInterface::getIsEnable, 1);
            wrapper.eq(SysInterface::getOrgId, orgId);
            List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
            List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());


            // 开始上机医嘱状态更新
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
                /*发布报告相关*/
                for (String webUrl : collect) {
                    // 调用修改状态接口
                    String updateUrl = webUrl + "/public/updateReportStatus";
                    Map<String, Object> updateMap = new HashMap<>();
                    updateMap.put("status", "0305");//上机
                    updateMap.put("reqNo", reqMain.getReqNo());
                    updateMap.put("username", sysUser.getUsername());
                    updateMap.put("realname", sysUser.getRealname());
                    updateMap.put("patType", reqMain.getPatType());
                    updateMap.put("chargeType", "1");
                    logger.info("开始上机更新医嘱状态入参为:" + JSONUtil.toJsonStr(updateMap));
                    HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                    // 调用执行医嘱确费接口
                    if ("3".equals(reqMain.getPatType())) {
                        String yzqfUrl = webUrl + "/yzqf";
                        HttpUtil.createPost(yzqfUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                    }

                    //添加系统参数判断是否需要重新获取计费信息，（东北双塔天健接口需求）2025-03-18
                    /*添加系统参数判断是否需要重新获取计费信息*/
                    SysParamParam sysp2222 = new SysParamParam();
                    sysp2222.setParamCode("xtxxcs");
                    sysp2222.setField("smsjsfxycxlqsq");
                    List<SysParamFieldValueDto> xtcs1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2222);
                    if (!xtcs1.isEmpty()) {
                        if ("1".equals(xtcs1.get(0).getValue())) {
                            Map<String, Object> updateMap11 = new HashMap<>();
                            updateMap11.put("reqNo", reqMain.getReqNo());
                            updateMap11.put("username", sysUser.getUsername());
                            updateMap11.put("realname", sysUser.getRealname());
                            updateMap11.put("orgId", sysUser.getOrgId());
                            updateMap11.put("patType", reqMain.getPatType());
                            logger.info("东北双塔后扫码开始执行上机计费接口:" + JSONUtil.toJsonStr(updateMap11));
                            String addFeeUrl = webUrl + "/public/beginCheckAddFee";
                            String body = HttpUtil.createPost(addFeeUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap11)).contentType("application/json").execute().body();
                            JSONObject jsonObject = new JSONObject(body);
                            JSONObject status = jsonObject.getJSONObject("status");
                            String code = status.get("code").toString();
                            if ("400".equals(code)) {
                                return Result.fail(jsonObject.getStr("data"));
                            }
                        }
                    }
                }
            }
            // 调用开始上机接口
            try {
                String code = "BEGIN_CHECK";
                List<SysInterfaceDict> allSysInterfaceDict = interfaceUtil.getAllSysInterfaceDict(code);
                if (CollectionUtils.isNotEmpty(allSysInterfaceDict)) {
                    for (SysInterfaceDict sysInterfaceDict : allSysInterfaceDict) {
                        try {
                            String webUrl = "";
                            if (sysInterfaceDict.getWebUrl().startsWith("http:")) {
                                webUrl = sysInterfaceDict.getWebUrl() + "/" + sysInterfaceDict.getCode();
                            } else {
                                webUrl = "http://" + sysInterfaceDict.getWebUrl() + "/" + sysInterfaceDict.getCode();
                            }
                            JSONObject q = new JSONObject();
                            q.set("reqNo", reqno);
                            q.set("username", sysUser.getUsername());
                            q.set("realname", sysUser.getRealname());
                            String returnMsg1 = HttpUtil.createPost(webUrl).body(JSONUtil.toJsonStr(q)).contentType("application/json").execute().body();
                            JSONObject reportObject = JSONUtil.parseObj(returnMsg1);
                            logger.info(returnMsg1);
                            JSONObject reportStatus = reportObject.getJSONObject("status");
                            String reportCode = reportStatus.get("code").toString();
                            if ("400".equals(reportCode)) {
                                return Result.fail("接口管理平台异常,请检查");
                            }
                        } catch (Exception e) {
                            logger.info("接口方法异常：" + sysInterfaceDict.getType());
                        }
                    }
                }
            } catch (Exception e) {
                logger.info("开始上机接口异常，请核实！");
                e.printStackTrace();
            }
        }
        // 改修改
        LambdaQueryWrapper<LabMaininfo> lambdaQueryWrappers = new LambdaQueryWrapper<>();
        lambdaQueryWrappers.eq(LabMaininfo::getSampleNo, labMaininfo.getSampleNo()).eq(LabMaininfo::getRptGroup, labMaininfo.getRptGroup()).eq(LabMaininfo::getSampleda, labMaininfo.getSampleda()).eq(LabMaininfo::getDelFlag, 0);
        boolean b = labMaininfoService.saveOrUpdate(labMaininfo, lambdaQueryWrappers);


        if (b) {

            List<LabRptresult> resultList = labMaininfo.getResultList();
            if (resultList == null) {
                resultList = new ArrayList<>();  // 防止 NPE
            }

            RptResultDto rptResultDto = new RptResultDto();
            rptResultDto.setLabRptresults(resultList);  // 关键赋值

            // 调用 Service
            labRptresultService.batchAddResultItemList(rptResultDto);

            /*标本流程状态记录*/
            // new Thread(() -> {
            // 重新计算检验结果
            labRptresultService.reCalcRptRssults(labMaininfo);
            // 上机之后插入状态信息
            LabMainState reqState1 = new LabMainState();
            reqState1.setMaininfoId(labMaininfo.getId());
            reqState1.setStateCode("90");
            reqState1.setStateValue("标本上机");
            reqState1.setOrgId(labMaininfo.getOrgId());
            labMainStateService.save(reqState1);

            if (StringUtils.isNotBlank(labMaininfo.getReqNo())) {
                /*标本状态*/
                LabReqMain rmEntry = labMainInfoServiceBak.getLabReqMainEntity(labMaininfo.getReqNo());
                LabReqState reqState = new LabReqState();
                reqState.setReqMainId(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getId() : "");
                reqState.setSampleda(labMaininfo.getSampleda());
                reqState.setSampleNo(labMaininfo.getSampleNo());
                reqState.setRptGroup(labMaininfo.getRptGroup());
                reqState.setReqNo(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getReqNo() : "");
                reqState.setOrgId(labMaininfo.getOrgId());
                reqState.setCreator(sysUser.getId());
                reqState.setStateCode("90");
                reqState.setStateValue("标本上机");
                String rmk = "【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "标本上机,标本号:" + (BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getReqNo() : "");
                reqState.setRemark(rmk);
                reqState.setSeq(labReqStateService.getMaxCount(labMaininfo.getReqNo()));
                labReqStateService.save(reqState);

                if (BeanUtil.isNotEmpty(rmEntry)) {
                    rmEntry.setState("90");
                    rmEntry.setStateNa("标本上机");
                    labReqMainService.saveOrUpdate(rmEntry);
                }
                // }).start();
            }
        }
        return Result.succ(1, "保存上机信息成功", labMaininfo);
    }


    // 标本扫码上机(修改信息) V2版本后扫码
    @Override
    public Result updateMaininfo(LabMaininfoCreateOrUpdateDto input) throws JsonProcessingException {
        LabMaininfo labMaininfo = input.getLabMaininfo();

        if (StringUtils.isBlank(input.getRptGroup())) {
            return Result.fail("报告单元为空");
        }
        if (StringUtils.isBlank(input.getSampleNo())) {
            return Result.fail("标本号为空");
        }
        if (BeanUtil.isEmpty(input.getSampleda())) {
            return Result.fail("检验日期为空");
        }
        if (BeanUtil.isEmpty(labMaininfo)) {
            return Result.fail("检验记录为空");
        }
        if (StringUtils.isNotBlank(labMaininfo.getPatNa())) {
            String apply = PinYinUtil.firstPinYinFun.apply(labMaininfo.getPatNa());
            labMaininfo.setPatPyName(apply);
        }
        LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);

        queryWrapper.eq(LabMaininfo::getSampleda, labMaininfo.getSampleda());
        queryWrapper.eq(LabMaininfo::getRptGroup, labMaininfo.getRptGroup());
        queryWrapper.eq(LabMaininfo::getSampleNo, labMaininfo.getSampleNo());

        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);
        Integer count = labMaininfos.size();
        // 申请信息
        LabReqMain rmEntry = null;
        if (StringUtils.isNotEmpty(input.getReqNo())) {
            rmEntry = labMainInfoServiceBak.getLabReqMainEntity(input.getReqNo());
            if (rmEntry == null && StringUtils.isNotBlank(input.getReqNo())) {
                try {
                    AddLabMaininfo addLabMaininfo = new AddLabMaininfo();
                    addLabMaininfo.setReqNo(input.getReqNo());
                    Result apiReqMainInfo = labMainInfoServiceBak.getApiReqMainInfo(addLabMaininfo);
                    if ("400".equals(apiReqMainInfo.getStatus().get("code") + "")) {
                        throw new RuntimeException(apiReqMainInfo.getStatus().get("msg") + "");
                    }
                } catch (Exception e) {
                    throw e;
                }
                rmEntry = labMainInfoServiceBak.getLabReqMainEntity(input.getReqNo());
                if (rmEntry == null) {
                    throw new RuntimeException("未获取到申请信息！");
                }
            }
        }

        if (count == 0) {
            AddLabMaininfo addLabMaininfo = new AddLabMaininfo();
            addLabMaininfo.setReqNo(input.getReqNo());
            addLabMaininfo.setSampleda(labMaininfo.getSampleda());
            addLabMaininfo.setRptGroup(labMaininfo.getRptGroup());
            addLabMaininfo.setSampleNo(labMaininfo.getSampleNo());
            return this.insertMaininfoByReqNo(addLabMaininfo);
            // input.getLabMaininfo().setTestTime(new Timestamp(System.currentTimeMillis()));
            // SysUser sysUser = RedisUserManager.getUser();
            // input.getLabMaininfo().setTestDoctor(sysUser.getUsername());
            // input.getLabMaininfo().setOrgId(sysUser.getOrgId());
            // if (BeanUtil.isEmpty(input.getLabMaininfo().getIsChk())) {
            //     input.getLabMaininfo().setIsChk(new BigDecimal(0));
            // }
            //
            // if (!BeanUtil.isEmpty(rmEntry)) {
            //     BeanUtil.copyProperties(rmEntry, input.getLabMaininfo(), "id", "isPrint", "creator", "editor", "createTime", "editTime", "delFlag");
            // }
            //
            // //改修改
            // LambdaQueryWrapper<LabMaininfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            // lambdaQueryWrapper.eq(LabMaininfo::getSampleNo, input.getLabMaininfo().getSampleNo());
            // lambdaQueryWrapper.eq(LabMaininfo::getRptGroup, input.getLabMaininfo().getRptGroup());
            // lambdaQueryWrapper.eq(LabMaininfo::getSampleda, input.getLabMaininfo().getSampleda());
            // lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
            // boolean b = labMaininfoService.saveOrUpdate(input.getLabMaininfo(), lambdaQueryWrapper);
            // if (b) {
            //     new Thread(() -> {
            //         labRptresultService.reCalcRptRssults(input.getLabMaininfo());
            //     }).start();
            //
            //     //labRptresultCalcService.reCalcReferRange1(labMaininfo);
            //
            //     //上机之后插入状态信息
            //     LabReqMain finalRmEntry = rmEntry;
            //     LabReqMain finalRmEntry1 = rmEntry;
            //     /*标本流程状态记录*/
            //     new Thread(() -> {
            //         LabMainState reqState1 = new LabMainState();
            //         reqState1.setMaininfoId(input.getLabMaininfo().getId());
            //         reqState1.setStateCode("90");
            //         reqState1.setStateValue("标本上机");
            //         reqState1.setRemark("由" + sysUser.getRealname() + "创建检验记录");
            //         labMainStateService.save(reqState1);
            //         if (BeanUtil.isNotEmpty(finalRmEntry)) {
            //             LabReqState reqState = new LabReqState();
            //             reqState.setReqMainId(BeanUtil.isNotEmpty(finalRmEntry) ? finalRmEntry.getId() : "");
            //             reqState.setSampleda(input.getLabMaininfo().getSampleda());
            //             reqState.setSampleNo(input.getLabMaininfo().getSampleNo());
            //             reqState.setRptGroup(input.getLabMaininfo().getRptGroup());
            //             reqState.setReqNo(BeanUtil.isNotEmpty(finalRmEntry) ? finalRmEntry.getReqNo() : "");
            //             reqState.setStateCode("90");
            //             reqState.setStateValue("标本上机");
            //             reqState.setOrgId(finalRmEntry.getOrgId());
            //             reqState.setCreator(sysUser.getId());
            //             String rmk = "【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "检验上机,标本号:" + (BeanUtil.isNotEmpty(finalRmEntry) ? finalRmEntry.getReqNo() : "");
            //             reqState.setRemark(rmk);
            //             reqState.setSeq(labReqStateService.getMaxCount(finalRmEntry.getReqNo()));
            //             labReqStateService.save(reqState);
            //
            //             if (BeanUtil.isNotEmpty(finalRmEntry1)) {
            //                 finalRmEntry1.setState("90");
            //                 finalRmEntry1.setStateNa("标本上机");
            //                 labReqMainService.saveOrUpdate(finalRmEntry1);
            //             }
            //         }
            //     }).start();
            //
            //     return Result.succ(1, "插入数据成功", getMainInfoById(input.getLabMaininfo().getId()));
            // } else {
            //     return Result.fail("插入数据失败！");
            // }
        } else {
            if (!BeanUtil.isEmpty(rmEntry)) {
                if (!BeanUtil.isEmpty(rmEntry)) {
                    try {
                        if (!BeanUtil.isEmpty(rmEntry.getIsCancel()) && rmEntry.getIsCancel().equals(1)) {
                            return Result.fail("当前标本已经作废," + rmEntry.getCancelReason());
                        }
                    } catch (Exception ex) {
                        // TODO
                    }

                    /*验证系统参数，无签收时间，禁止上机*/
                    SysParamParam sysp1 = new SysParamParam();
                    sysp1.setParamCode("xtxxcs");
                    sysp1.setField("wqssjbbjzsj");
                    List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                    if (!r1.isEmpty()) {
                        if ("1".equals(r1.get(0).getValue()) && BeanUtil.isEmpty(rmEntry.getSignTime())) {
                            return Result.fail("无签收时间标本禁止上机");
                        }
                    }

                    // 住院无签收时间标本禁止上机
                    /*验证系统参数，无签收时间，禁止上机*/
                    sysp1 = new SysParamParam();
                    sysp1.setParamCode("xtxxcs");
                    sysp1.setField("zywqssjbbjzsj");
                    r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                    if (!r1.isEmpty()) {
                        if ("1".equals(r1.get(0).getValue()) && BeanUtil.isEmpty(rmEntry.getSignTime()) && !BeanUtil.isEmpty(rmEntry.getPatType()) && rmEntry.getPatType().equals("3")) {
                            return Result.fail("住院无签收时间标本禁止上机");
                        }
                    }

                    /*验证系统参数，无采样时间,禁止上机*/
                    sysp1 = new SysParamParam();
                    sysp1.setParamCode("xtxxcs");
                    sysp1.setField("wcysjjzsj");
                    r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                    if (!r1.isEmpty()) {
                        String value = r1.get(0).getValue();
                        if (ToolsUtils.isNotEmpty(value)) {
                            List<String> listValue = getListValueMethod(value);
                            if (ToolsUtils.isNotEmpty(rmEntry.getPatType()) && listValue.contains(rmEntry.getPatType()) && ToolsUtils.isEmpty(rmEntry.getSamplingTime())) {
                                return Result.fail("无采样时间禁止上机");
                            }
                        }
                    }

                    /*验证系统参数，无采样人,禁止上机*/
                    sysp1 = new SysParamParam();
                    sysp1.setParamCode("xtxxcs");
                    sysp1.setField("wcyrjzsj");
                    r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                    if (!r1.isEmpty()) {
                        String value = r1.get(0).getValue();
                        if (ToolsUtils.isNotEmpty(value)) {
                            List<String> listValue = getListValueMethod(value);
                            if (ToolsUtils.isNotEmpty(rmEntry.getPatType()) && listValue.contains(rmEntry.getPatType()) && ToolsUtils.isEmpty(rmEntry.getSamplingDoctor())) {
                                return Result.fail("无采样人禁止上机");
                            }
                        }
                    }

                    //---报告单元
                    /*验证系统参数，无采样时间,禁止上机*/
                    sysp1 = new SysParamParam();
                    sysp1.setParamCode("bgdyxtcs");
                    sysp1.setField("bgdywcysjjzsj");
                    sysp1.setClassifyCode(input.getRptGroup());

                    r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                    if (!r1.isEmpty()) {
                        String value = r1.get(0).getValue();
                        if (ToolsUtils.isNotEmpty(value)) {
                            List<String> listValue = getListValueMethod(value);
                            if (ToolsUtils.isNotEmpty(rmEntry.getPatType()) && listValue.contains(rmEntry.getPatType()) && ToolsUtils.isEmpty(rmEntry.getSamplingTime())) {
                                return Result.fail("无采样时间禁止上机");
                            }
                        }
                    }
                    //---报告单元
                    /*验证系统参数，无采样人,禁止上机*/
                    sysp1 = new SysParamParam();
                    sysp1.setParamCode("bgdyxtcs");
                    sysp1.setField("bgdywcyrjzsj");
                    sysp1.setClassifyCode(input.getRptGroup());
                    r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                    if (!r1.isEmpty()) {
                        String value = r1.get(0).getValue();
                        if (ToolsUtils.isNotEmpty(value)) {
                            List<String> listValue = getListValueMethod(value);
                            if (ToolsUtils.isNotEmpty(rmEntry.getPatType()) && listValue.contains(rmEntry.getPatType()) && ToolsUtils.isEmpty(rmEntry.getSamplingDoctor())) {
                                return Result.fail("无采样人禁止上机");
                            }
                        }
                    }
                }

                /*有条码申请，检验记录无条码号，需要赋值 申请拷贝到检验记录*/
                if (StringUtils.isNotBlank(rmEntry.getReqNo()) && StringUtils.isBlank(labMaininfo.getReqNo())) {
                    BeanUtil.copyProperties(rmEntry, labMaininfo, "id", "sampleNo", "isPrint", "creator", "editor", "createTime", "editTime", "delFlag");
                }
                /*有条码申请，检验记录有条码号，但是条码号不相等，需要赋值 申请拷贝到检验记录*/
                if (StringUtils.isNotBlank(rmEntry.getReqNo()) && StringUtils.isNotBlank(labMaininfo.getReqNo()) && !rmEntry.getReqNo().equals(labMaininfo.getReqNo())) {
                    BeanUtil.copyProperties(rmEntry, labMaininfo, "id", "sampleNo", "isPrint", "creator", "editor", "createTime", "editTime", "delFlag");
                }
            }


            //扫码上机时更新上机时间
            // LambdaQueryWrapper<LabMaininfo> infoWrapper = new LambdaQueryWrapper<>();
            // infoWrapper.eq(LabMaininfo::getSampleda,input.getSampleda())
            //         .eq(LabMaininfo::getSampleNo,input.getSampleNo())
            //         .eq(LabMaininfo::getRptGroup,input.getRptGroup())
            //         .eq(LabMaininfo::getDelFlag,0);
            //
            // LabMaininfo maininfo = labMaininfoMapper.selectOne(infoWrapper);

            if(StringUtils.isNotEmpty(input.getReqNo()) && StringUtils.isEmpty(labMaininfos.get(0).getReqNo())){
                input.getLabMaininfo().setTestTime(new Timestamp(new Date().getTime()));
            }

            SysUser sysUser = RedisUserManager.getUser();
            LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysInterface::getDelFlag, 0);
            wrapper.eq(SysInterface::getIsEnable, 1);
            wrapper.eq(SysInterface::getOrgId, rmEntry.getOrgId());
            List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
            List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
                /*发布报告相关*/
                for (String webUrl : collect) {
                    //添加系统参数判断是否需要重新获取计费信息，（东北双塔天健接口需求）2025-03-18
                    /*添加系统参数判断是否需要重新获取计费信息*/
                    SysParamParam sysp111 = new SysParamParam();
                    sysp111.setParamCode("xtxxcs");
                    sysp111.setField("smsjsfxycxlqsq");
                    List<SysParamFieldValueDto> xtcs1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp111);
                    if (!xtcs1.isEmpty()) {
                        if ("1".equals(xtcs1.get(0).getValue())) {
                            Map<String, Object> updateMap = new HashMap<>();
                            updateMap.put("reqNo", rmEntry.getReqNo());
                            updateMap.put("username", sysUser.getUsername());
                            updateMap.put("realname", sysUser.getRealname());
                            updateMap.put("patType", rmEntry.getPatType());
                            updateMap.put("orgId", sysUser.getOrgId());
                            logger.info("开始执行上机计费接口:" + JSONUtil.toJsonStr(updateMap));
                            String addFeeUrl = webUrl + "/public/beginCheckAddFee";
                            String body = HttpUtil.createPost(addFeeUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                            JSONObject jsonObject = new JSONObject(body);
                            JSONObject status = jsonObject.getJSONObject("status");
                            String code = status.get("code").toString();
                            if ("400".equals(code)) {
                                return Result.fail(jsonObject.getStr("data"));
                            }
                        }
                    }
                    if (!"4".equals(labMaininfo.getPatType())) {
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.set("id", labMaininfo.getId());
                            jsonObject.set("orgId", sysUser.getOrgId());
                            jsonObject.set("reqNo", labMaininfo.getReqNo());
                            jsonObject.set("username", sysUser.getUsername());
                            jsonObject.set("realname", sysUser.getRealname());
                            String body = HttpUtil.createPost(webUrl + "/lisRestFul/noticeHisFee").body(JSONUtil.toJsonStr(jsonObject)).contentType("application/json").execute().body();
                            logger.info(body);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            // 插入模板数据
            TemplateParams tmpParam = new TemplateParams();
            tmpParam.setMaininfoId(labMaininfo.getId());
            tmpParam.setRptGroup(labMaininfo.getRptGroup());
            tmpParam.setSampleda(labMaininfo.getSampleda());
            tmpParam.setSampleNo(labMaininfo.getSampleNo());
            tmpParam.setReqNo(input.getReqNo());
            List<LabRptresult> rptresultList = labTemplateService.batchDefItemDictAndTemplate(tmpParam);

            if (rptresultList != null) {
                labMaininfo.setResultList(rptresultList);
            }

            return Result.succ(1, "请求完成", labMaininfo);


            // int i = labMaininfoMapper.updateById(input.getLabMaininfo());
            // if ((input.getLabMaininfo().getIsChk() == null || input.getLabMaininfo().getIsChk().intValue() < 2) && i > 0) {
            //
            //     //插入模板数据
            //     TemplateParams tmpParam = new TemplateParams();
            //     tmpParam.setMaininfoId(input.getLabMaininfo().getId());
            //     tmpParam.setRptGroup(input.getLabMaininfo().getRptGroup());
            //     tmpParam.setSampleda(input.getLabMaininfo().getSampleda());
            //     tmpParam.setSampleNo(input.getLabMaininfo().getSampleNo());
            //     tmpParam.setReqNo(input.getLabMaininfo().getReqNo());
            //     labTemplateService.batchInsertDefItemDictAndTemplate(tmpParam);
            //     //重新计算检验结果
            //     //labRptresultCalcService.reCalcReferRange1(labMaininfo);
            //     new Thread(() -> {
            //         labRptresultService.reCalcRptRssults(input.getLabMaininfo());
            //     }).start();
            //
            //     return Result.succ(1, "修改据成功", getMainInfoById(input.getLabMaininfo().getId()));
            // } else {
            //     return Result.succ(1, "修改据成功", getMainInfoById(input.getLabMaininfo().getId()));
            // }
        }

    }


    @Override
    public Result findLabReqMainOrMainfoList(LabReqMainDto labReqMain) {

        Page<LabReqMainQuery> page = new Page<>();
        page.setCurrent(labReqMain.getPageIndex());
        page.setSize(labReqMain.getPageSize());
        MPJLambdaWrapper<LabReqMainQuery> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabReqMainQuery.class);
        lambdaQueryWrapper.selectAs(LabMaininfoQuery::getTestTime, LabReqMainQuery::getTestTime);
        lambdaQueryWrapper.selectAs("test", SysUser::getRealname, LabReqMainQuery::getTestDoctorNa);
        lambdaQueryWrapper.selectAs(LabMaininfoQuery::getChkTime, LabReqMainQuery::getChkTime);
        lambdaQueryWrapper.selectAs("chk", SysUser::getRealname, LabReqMainQuery::getChkDoctorNa);
        lambdaQueryWrapper.selectAs(LabMaininfoQuery::getSampleNo, LabReqMainQuery::getSampleNo);
        lambdaQueryWrapper.selectAs(LabMaininfoQuery::getRptGroup, LabReqMainQuery::getRptGroup);
        lambdaQueryWrapper.selectAs(LabMaininfoQuery::getSampleda, LabReqMainQuery::getSampleda);
        lambdaQueryWrapper.leftJoin(LabMaininfoQuery.class, LabMaininfoQuery::getReqNo, LabReqMainQuery::getReqNo);
        lambdaQueryWrapper.leftJoin(SysUser.class, "test", p -> p.eq(SysUser::getUsername, LabMaininfoQuery::getTestDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        lambdaQueryWrapper.leftJoin(SysUser.class, "chk", p -> p.eq(SysUser::getUsername, LabMaininfoQuery::getChkDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        lambdaQueryWrapper.eq(LabReqMainQuery::getDelFlag, 0);
        if (ToolsUtils.isNotEmpty(labReqMain.getStartTime())) {
            Timestamp startTime = Timestamp.valueOf(labReqMain.getStartTime());
            // 申请时间
            lambdaQueryWrapper.ge(LabReqMainQuery::getReqTime, startTime);
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getEndTime())) {
            Timestamp endTime = Timestamp.valueOf(labReqMain.getEndTime());
            lambdaQueryWrapper.le(LabReqMainQuery::getReqTime, endTime);
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getReqNo())) {
            lambdaQueryWrapper.eq(LabReqMainQuery::getReqNo, labReqMain.getReqNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getBedNo())) {
            lambdaQueryWrapper.eq(LabReqMainQuery::getBedNo, labReqMain.getBedNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatNo())) {
            lambdaQueryWrapper.eq(LabReqMainQuery::getPatNo, labReqMain.getPatNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatNa())) {
            lambdaQueryWrapper.like(LabReqMainQuery::getPatNa, labReqMain.getPatNa());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getIdNo())) {
            lambdaQueryWrapper.eq(LabReqMainQuery::getIdNo, labReqMain.getIdNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getTelNo())) {
            lambdaQueryWrapper.like(LabReqMainQuery::getTelNo, labReqMain.getTelNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getTestPurpose())) {
            lambdaQueryWrapper.like(LabReqMainQuery::getTestPurpose, labReqMain.getTestPurpose());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getReqDept())) {
            lambdaQueryWrapper.eq(LabReqMainQuery::getReqDept, labReqMain.getReqDept());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatType())) {
            lambdaQueryWrapper.eq(LabReqMainQuery::getPatType, labReqMain.getPatType());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getCompanyCode())) {
            lambdaQueryWrapper.eq(LabReqMainQuery::getInspectCompany, labReqMain.getCompanyCode());
        }
        Page<LabReqMainQuery> list = labReqMainQueryMapper.selectJoinPage(page, LabReqMainQuery.class, lambdaQueryWrapper);

        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        for (LabReqMainQuery reqMain : (List<LabReqMainQuery>) list.getRecords()) {
            if (StringUtils.isNotBlank(reqMain.getPatType()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(reqMain.getPatType())).findFirst().ifPresent(stringObjectMap -> reqMain.setPatTypeNa((String) stringObjectMap.get("name")));
            }
        }

        return Result.succ(1, "查询成功", list);
    }

    @Override
    public Result barcodePrintQueryOrMaininfo(PrintBarcodeDto dto) {
        // MPJLambdaWrapper<LabHisReq> queryWrapper = new MPJLambdaWrapper<>();
        // queryWrapper.selectAll(LabHisReq.class).eq(LabHisReq::getDelFlag, 0);

        MPJLambdaWrapper<LabReqMainQuery> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabReqMainQuery.class);

        queryWrapper.selectAs("smpt", LabSampleType::getSampleTypeName, LabReqMainQuery::getSampleTypeNa);
        queryWrapper.selectAs("dept", SysOrgDepartment::getName, LabReqMainQuery::getReqDeptNa);
        queryWrapper.selectAs("reqDoc", PubEmployee::getName, LabReqMainQuery::getReqDoctorNa);
        queryWrapper.selectAs("sampDoc", PubEmployee::getName, LabReqMainQuery::getSamplingDoctorNa);
        queryWrapper.selectAs("pros", LabProcessSet::getNodeName, LabReqMainQuery::getStateNa);
        queryWrapper.selectAs(LabMaininfoQuery::getSampleNo, LabReqMainQuery::getSampleNo);
        queryWrapper.selectAs(LabMaininfoQuery::getRptGroup, LabReqMainQuery::getRptGroup);
        queryWrapper.selectAs(LabMaininfoQuery::getSampleda, LabReqMainQuery::getSampleda);

        String patNo = dto.getPatNo();
        if (!StringUtils.isEmpty(patNo)) {
            queryWrapper.eq(LabReqMainQuery::getPatNo, patNo);
        }
        String reqNo = dto.getReqNo();
        if (!StringUtils.isEmpty(reqNo)) {
            queryWrapper.eq(LabReqMainQuery::getReqNo, reqNo);
        }
        String bedNo = dto.getBedNo();
        if (!StringUtils.isEmpty(bedNo)) {
            queryWrapper.eq(LabReqMainQuery::getBedNo, bedNo);
        }
        if (ToolsUtils.isNotEmpty(dto.getPatType()) && dto.getPatType().size() > 0) {
            queryWrapper.in(LabReqMainQuery::getPatType, dto.getPatType());
        }
        List<String> deptList = dto.getDeptNo();
        if (deptList.size() > 0) {
            //2025年1月14号蔡总提需求银丰项目修改
            queryWrapper.and(p -> p.in(LabReqMainQuery::getReqDept, deptList).or().in(LabReqMainQuery::getReqWard, deptList));
//            queryWrapper.in(LabReqMainQuery::getReqDept, deptList);
        }
        String patNa = dto.getPatNa();
        if (!StringUtils.isEmpty(patNa)) {
            queryWrapper.eq(LabReqMainQuery::getPatNa, patNa);
        }
        String idNo = dto.getIDNo();
        if (!StringUtils.isEmpty(idNo)) {
            queryWrapper.eq(LabReqMainQuery::getIdNo, idNo);
        }
        // queryWrapper
        //         .ge(LabHisReq::getReqTime, dto.getReqDateS())
        //         .le(LabHisReq::getReqTime, dto.getReqDateE());
        queryWrapper.between(LabReqMainQuery::getReqTime, dto.getReqDateS(), dto.getReqDateE());
        queryWrapper.leftJoin(LabMaininfoQuery.class, LabMaininfoQuery::getReqNo, LabReqMainQuery::getReqNo);
        queryWrapper.leftJoin(LabSampleType.class, "smpt", p -> p.eq(LabSampleType::getSampleTypeCode, LabReqMainQuery::getSampleType).eq(LabSampleType::getDelFlag, 0).eq(LabSampleType::getOrgId, LabReqMainQuery::getOrgId).isNotNull(LabSampleType::getSampleTypeCode));
        queryWrapper.leftJoin(SysOrgDepartment.class, "dept", p -> p.eq(SysOrgDepartment::getCode, LabReqMainQuery::getReqDept).eq(SysOrgDepartment::getDelFlag, 0).eq(SysOrgDepartment::getOrgId, LabReqMainQuery::getOrgId).isNotNull(SysOrgDepartment::getCode));
        queryWrapper.leftJoin(PubEmployee.class, "reqDoc", p -> p.eq(PubEmployee::getCode, LabReqMainQuery::getReqDoctor).eq(PubEmployee::getDelFlag, 0).eq(PubEmployee::getOrgId, LabReqMainQuery::getOrgId).isNotNull(PubEmployee::getCode));
        queryWrapper.leftJoin(PubEmployee.class, "sampDoc", p -> p.eq(PubEmployee::getCode, LabReqMainQuery::getSamplingDoctor).eq(PubEmployee::getDelFlag, 0).eq(PubEmployee::getOrgId, LabReqMainQuery::getOrgId).isNotNull(PubEmployee::getCode));
        // StringBuffer existsSql = new StringBuffer("SELECT 1 FROM LAB_REQ_PRINT p WHERE t.ID = p.HIS_REQ_ID ");
        // queryWrapper.notExists(existsSql.toString());
        queryWrapper.leftJoin(LabProcessSet.class, "pros", p -> p.eq(LabProcessSet::getCode, LabReqMainQuery::getState).eq(LabProcessSet::getDelFlag, 0));
        List<LabReqMainQuery> labReqMainList = labReqMainQueryMapper.selectList(queryWrapper);

        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();
        for (LabReqMainQuery maininfo : labReqMainList) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));
            }
        }

        //labReqMainList根据printTime倒序空的在后面


        // 对列表按 printTime 字段进行降序排序

        List<LabReqMainQuery> collect = labReqMainList.stream()
                .sorted(Comparator.comparing(LabReqMainQuery::getPrintTime, Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
                .collect(Collectors.toList());

        // Comparator<LabReqMainQuery> comparing = Comparator.comparing(LabReqMainQuery::getPrintTime);
        // List<LabReqMainQuery> collect = labReqMainList.stream().sorted(comparing.reversed()).collect(Collectors.toList());

        return Result.succ(1, "查询成功", collect);
    }

    @Override
    public Result findLabReqMainReHistory(LabMaininfoPageDto maininfoPageDto) {

        SysUser sysUser = RedisUserManager.getUser();
        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabReqMain.class);
        queryWrapper.selectAs("pros", LabProcessSet::getDisplayColor, LabReqMain::getDisplayColor);
        queryWrapper.selectAs("pros", LabProcessSet::getNodeName, LabReqMain::getStateNa);
        queryWrapper.leftJoin(LabProcessSet.class, "pros", p -> p.eq(LabProcessSet::getCode, LabReqMain::getState).eq(LabProcessSet::getDelFlag, 0));

        queryWrapper.eq(LabReqMain::getDelFlag, 0);
        //queryWrapper.ge(LabReqMain::getState, 69);//查询状态含70以上的
        String states = maininfoPageDto.getStates();
        //ge:70,lt:90
        if (ToolsUtils.isNotEmpty(states)) {
            String[] stateArr = states.split(",");
            if (stateArr.length > 0) {
                queryWrapper.and(p -> {
                    for (int i = 0; i < stateArr.length; i++) {
                        String[] state = stateArr[i].split(":");
                        if (state.length > 1) {
                            if ("ge".equals(state[0])) {
                                p.ge(LabReqMain::getState, Integer.valueOf(state[1]));
                            }
                            if ("gt".equals(state[0])) {
                                p.gt(LabReqMain::getState, Integer.valueOf(state[1]));
                            }
                            if ("le".equals(state[0])) {
                                p.le(LabReqMain::getState, Integer.valueOf(state[1]));
                            }
                            if ("lt".equals(state[0])) {
                                p.lt(LabReqMain::getState, Integer.valueOf(state[1]));
                            }
                        }
                    }
                });
            }
        }

        String state = maininfoPageDto.getState();
        if (ToolsUtils.isNotEmpty(state)) {
            queryWrapper.eq(LabReqMain::getState, Integer.valueOf(state));
        }

        //isSign 全部 null, 0 未签，1 已签
        Integer isSign = maininfoPageDto.getIsSign();
        if (ToolsUtils.isNotEmpty(isSign)) {
            if (isSign == 1) {
                queryWrapper.eq(LabReqMain::getIsSign, isSign);
            } else if (isSign == 0) {
                queryWrapper.and(p -> p.eq(LabReqMain::getIsSign, isSign).or().isNull(LabReqMain::getIsSign));
            }
        }
        //isSampling 全部 null, 0 未签，1 已签
        Integer isSampling = maininfoPageDto.getIsSampling();
        if (ToolsUtils.isNotEmpty(isSampling)) {
            if (isSampling == 1) {
                queryWrapper.eq(LabReqMain::getIsSampling, isSampling);
            } else if (isSampling == 0) {
                queryWrapper.and(p -> p.eq(LabReqMain::getIsSampling, isSampling).or().isNull(LabReqMain::getIsSampling));
            }
        }

        if (ToolsUtils.isNotEmpty(maininfoPageDto.getOrgId())) {
            queryWrapper.eq(SysEventLog::getOrgId, sysUser.getOrgId());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getReqNo())) {
            queryWrapper.eq(LabReqMain::getReqNo, maininfoPageDto.getReqNo());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatId())) {
            queryWrapper.eq(LabReqMain::getPatId, maininfoPageDto.getPatId());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatNa())) {
            queryWrapper.eq(LabReqMain::getPatNa, maininfoPageDto.getPatNa());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatNo())) {
            queryWrapper.like(LabReqMain::getPatNo, maininfoPageDto.getPatNo());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getSamplingTimeS()) && ToolsUtils.isNotEmpty(maininfoPageDto.getSamplingTimeE())) {
            queryWrapper.ge(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeS()).getTime()));
            queryWrapper.le(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeE()).getTime()));
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getSignTimeS()) && ToolsUtils.isNotEmpty(maininfoPageDto.getSignTimeE())) {
            if (StringUtils.isNotBlank(maininfoPageDto.getTimeType())) {
                //1:申请时间+签收时间 2申请时间 3签收时间
                if (maininfoPageDto.getTimeType().equals("1")) {
                    queryWrapper.ge(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeS()).getTime()));
                    queryWrapper.le(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeE()).getTime()));
                    queryWrapper.ge(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeS()).getTime()));
                    queryWrapper.le(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeE()).getTime()));
                } else if (maininfoPageDto.getTimeType().equals("2")) {
                    queryWrapper.ge(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeS()).getTime()));
                    queryWrapper.le(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeE()).getTime()));
                } else {
                    queryWrapper.ge(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeS()).getTime()));
                    queryWrapper.le(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeE()).getTime()));
                }
            } else {
                queryWrapper.ge(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeS()).getTime()));
                queryWrapper.le(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeE()).getTime()));
            }
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getReqTimeS()) && ToolsUtils.isNotEmpty(maininfoPageDto.getReqTimeE())) {
            queryWrapper.ge(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(maininfoPageDto.getReqTimeS()).getTime()));
            queryWrapper.le(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(maininfoPageDto.getReqTimeE()).getTime()));
        }
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        //Page<LabReqMain> reqPageList = labReqMainMapper.selectPage(page, queryWrapper);
        List<LabReqMain> labReqMainList = labReqMainMapper.selectList(queryWrapper);

        for (LabReqMain reqMain : labReqMainList) {
            if (StringUtils.isNotBlank(reqMain.getSex()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(reqMain.getSex())).findFirst().ifPresent(stringObjectMap -> reqMain.setSexNa((String) stringObjectMap.get("name")));
            }
        }

        return Result.succ(1, "查询成功", labReqMainList);
    }

    @Override
    public Result findLabReqMainReHistoryPage(LabMaininfoPageDto maininfoPageDto) {

        Page<LabReqMain> page = new Page<LabReqMain>();
        page.setCurrent(maininfoPageDto.getPageIndex());
        page.setSize(maininfoPageDto.getPageSize());
        SysUser sysUser = RedisUserManager.getUser();
        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabReqMain.class);
        queryWrapper.selectAs("pros", LabProcessSet::getDisplayColor, LabReqMain::getDisplayColor);
        queryWrapper.selectAs("pros", LabProcessSet::getNodeName, LabReqMain::getStateNa);
        queryWrapper.leftJoin(LabProcessSet.class, "pros", p -> p.eq(LabProcessSet::getCode, LabReqMain::getState).eq(LabProcessSet::getDelFlag, 0));

        queryWrapper.eq(LabReqMain::getDelFlag, 0);
        //queryWrapper.ge(LabReqMain::getState, 69);//查询状态含70以上的
        String states = maininfoPageDto.getStates();
        //ge:70,lt:90
        if (ToolsUtils.isNotEmpty(states)) {
            String[] stateArr = states.split(",");
            if (stateArr.length > 0) {
                queryWrapper.and(p -> {
                    for (int i = 0; i < stateArr.length; i++) {
                        String[] state = stateArr[i].split(":");
                        if (state.length > 1) {
                            if ("ge".equals(state[0])) {
                                p.ge(LabReqMain::getState, Integer.valueOf(state[1]));
                            }
                            if ("gt".equals(state[0])) {
                                p.gt(LabReqMain::getState, Integer.valueOf(state[1]));
                            }
                            if ("le".equals(state[0])) {
                                p.le(LabReqMain::getState, Integer.valueOf(state[1]));
                            }
                            if ("lt".equals(state[0])) {
                                p.lt(LabReqMain::getState, Integer.valueOf(state[1]));
                            }
                        }
                    }
                });
            }
        }

        String state = maininfoPageDto.getState();
        if (ToolsUtils.isNotEmpty(state)) {
            queryWrapper.eq(LabReqMain::getState, Integer.valueOf(state));
        }

        //isSign 全部 null, 0 未签，1 已签
        Integer isSign = maininfoPageDto.getIsSign();
        if (ToolsUtils.isNotEmpty(isSign)) {
            if (isSign == 1) {
                queryWrapper.eq(LabReqMain::getIsSign, isSign);
            } else if (isSign == 0) {
                queryWrapper.and(p -> p.eq(LabReqMain::getIsSign, isSign).or().isNull(LabReqMain::getIsSign));
            }
        }
        //isSampling 全部 null, 0 未签，1 已签
        Integer isSampling = maininfoPageDto.getIsSampling();
        if (ToolsUtils.isNotEmpty(isSampling)) {
            if (isSampling == 1) {
                queryWrapper.eq(LabReqMain::getIsSampling, isSampling);
            } else if (isSampling == 0) {
                queryWrapper.and(p -> p.eq(LabReqMain::getIsSampling, isSampling).or().isNull(LabReqMain::getIsSampling));
            }
        }

        if (ToolsUtils.isNotEmpty(maininfoPageDto.getOrgId())) {
            queryWrapper.eq(SysEventLog::getOrgId, sysUser.getOrgId());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatType())) {
            queryWrapper.eq(LabReqMain::getPatType, maininfoPageDto.getPatType());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getReqNo())) {
            queryWrapper.eq(LabReqMain::getReqNo, maininfoPageDto.getReqNo());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatId())) {
            queryWrapper.eq(LabReqMain::getPatId, maininfoPageDto.getPatId());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatNa())) {
            queryWrapper.eq(LabReqMain::getPatNa, maininfoPageDto.getPatNa());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatNo())) {
            queryWrapper.like(LabReqMain::getPatNo, maininfoPageDto.getPatNo());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getSamplingTimeS()) && ToolsUtils.isNotEmpty(maininfoPageDto.getSamplingTimeE())) {
            queryWrapper.ge(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeS()).getTime()));
            queryWrapper.le(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeE()).getTime()));
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getSignTimeS()) && ToolsUtils.isNotEmpty(maininfoPageDto.getSignTimeE())) {
            if (StringUtils.isNotBlank(maininfoPageDto.getTimeType())) {
                //1:申请时间+签收时间 2申请时间 3签收时间
                if (maininfoPageDto.getTimeType().equals("1")) {
                    queryWrapper.ge(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeS()).getTime()));
                    queryWrapper.le(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeE()).getTime()));
                    queryWrapper.ge(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeS()).getTime()));
                    queryWrapper.le(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeE()).getTime()));
                } else if (maininfoPageDto.getTimeType().equals("2")) {
                    queryWrapper.ge(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeS()).getTime()));
                    queryWrapper.le(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeE()).getTime()));
                } else {
                    queryWrapper.ge(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeS()).getTime()));
                    queryWrapper.le(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeE()).getTime()));
                }
            } else {
                queryWrapper.ge(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeS()).getTime()));
                queryWrapper.le(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeE()).getTime()));
            }
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getReqTimeS()) && ToolsUtils.isNotEmpty(maininfoPageDto.getReqTimeE())) {
            queryWrapper.ge(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(maininfoPageDto.getReqTimeS()).getTime()));
            queryWrapper.le(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(maininfoPageDto.getReqTimeE()).getTime()));
        }
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        Page<LabReqMain> reqPageList = labReqMainMapper.selectPage(page, queryWrapper);

        for (LabReqMain reqMain : (List<LabReqMain>) reqPageList.getRecords()) {
            if (StringUtils.isNotBlank(reqMain.getSex()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(reqMain.getSex())).findFirst().ifPresent(stringObjectMap -> reqMain.setSexNa((String) stringObjectMap.get("name")));
            }
        }

        return Result.succ(1, "查询成功", reqPageList);
    }


    public LabReqMain getLabReqMainEntity(String reqno) {
        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabReqMain.class)
                .selectAs(LabSampleType::getSampleTypeName, LabReqMain::getSampleTypeNa)
                .leftJoin(LabSampleType.class, LabSampleType::getSampleTypeCode, LabReqMain::getSampleType)
                .eq(LabReqMain::getDelFlag, 0)
                .eq(LabReqMain::getReqNo, reqno);
        queryWrapper.orderByDesc(LabReqMain::getCreateTime);
        List<LabReqMain> reqMains = labReqMainMapper.selectList(queryWrapper);

        return reqMains.isEmpty() ? null : reqMains.get(0);
    }

    public Result exportOrMainInfoExcel(LabReqMainDto labReqMain) {
        MPJLambdaWrapper<LabReqMainQuery> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabReqMainQuery.class);
        lambdaQueryWrapper.selectAs(LabMaininfoQuery::getTestTime, LabReqMainQuery::getTestTime);
        lambdaQueryWrapper.selectAs("test", SysUser::getRealname, LabReqMainQuery::getTestDoctorNa);
        lambdaQueryWrapper.selectAs(LabMaininfoQuery::getChkTime, LabReqMainQuery::getChkTime);
        lambdaQueryWrapper.selectAs("chk", SysUser::getRealname, LabReqMainQuery::getChkDoctorNa);
        lambdaQueryWrapper.selectAs(LabMaininfoQuery::getSampleNo, LabReqMainQuery::getSampleNo);
        lambdaQueryWrapper.selectAs(LabMaininfoQuery::getRptGroup, LabReqMainQuery::getRptGroup);
        lambdaQueryWrapper.selectAs(LabMaininfoQuery::getSampleda, LabReqMainQuery::getSampleda);
        lambdaQueryWrapper.leftJoin(LabMaininfoQuery.class, LabMaininfoQuery::getReqNo, LabReqMainQuery::getReqNo);
        lambdaQueryWrapper.leftJoin(SysUser.class, "test", p -> p.eq(SysUser::getUsername, LabMaininfoQuery::getTestDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        lambdaQueryWrapper.leftJoin(SysUser.class, "chk", p -> p.eq(SysUser::getUsername, LabMaininfoQuery::getChkDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        lambdaQueryWrapper.eq(LabReqMainQuery::getDelFlag, 0);
        if (ToolsUtils.isNotEmpty(labReqMain.getStartTime())) {
            Timestamp startTime = Timestamp.valueOf(labReqMain.getStartTime());
            // 申请时间
            lambdaQueryWrapper.ge(LabReqMainQuery::getReqTime, startTime);
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getEndTime())) {
            Timestamp endTime = Timestamp.valueOf(labReqMain.getEndTime());
            lambdaQueryWrapper.le(LabReqMainQuery::getReqTime, endTime);
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getReqNo())) {
            lambdaQueryWrapper.eq(LabReqMainQuery::getReqNo, labReqMain.getReqNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getBedNo())) {
            lambdaQueryWrapper.eq(LabReqMainQuery::getBedNo, labReqMain.getBedNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatNo())) {
            lambdaQueryWrapper.eq(LabReqMainQuery::getPatNo, labReqMain.getPatNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatNa())) {
            lambdaQueryWrapper.like(LabReqMainQuery::getPatNa, labReqMain.getPatNa());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getIdNo())) {
            lambdaQueryWrapper.eq(LabReqMainQuery::getIdNo, labReqMain.getIdNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getTelNo())) {
            lambdaQueryWrapper.like(LabReqMainQuery::getTelNo, labReqMain.getTelNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getTestPurpose())) {
            lambdaQueryWrapper.like(LabReqMainQuery::getTestPurpose, labReqMain.getTestPurpose());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getReqDept())) {
            lambdaQueryWrapper.eq(LabReqMainQuery::getReqDept, labReqMain.getReqDept());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatType())) {
            lambdaQueryWrapper.eq(LabReqMainQuery::getPatType, labReqMain.getPatType());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getCompanyCode())) {
            lambdaQueryWrapper.eq(LabReqMainQuery::getInspectCompany, labReqMain.getCompanyCode());
        }
        List<LabReqMainQuery> list = labReqMainQueryMapper.selectList(lambdaQueryWrapper);

        int i = 1;
        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        for (LabReqMainQuery reqMain : list) {
            if (StringUtils.isNotBlank(reqMain.getPatType()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(reqMain.getPatType())).findFirst().ifPresent(stringObjectMap -> reqMain.setPatTypeNa((String) stringObjectMap.get("name")));
            }
        }
        return Result.succ(1, "查询成功", list);
    }

    @Override
    public Result exportReqExcel(LabReqMainDto labReqMain) {

        MPJLambdaWrapper<LabReqMain> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabReqMain.class);
        lambdaQueryWrapper.selectAs("req", PubEmployee::getName, LabReqMain::getReqDoctorName);
        lambdaQueryWrapper.selectAs(SysOrgDepartment::getName, LabReqMain::getReqDeptNa);
        lambdaQueryWrapper.leftJoin(PubEmployee.class, "req", p -> p.eq(PubEmployee::getCode, LabReqMain::getReqDoctor).eq(PubEmployee::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(SysOrgDepartment.class, p -> p.eq(SysOrgDepartment::getCode, LabReqMain::getReqDept).eq(SysOrgDepartment::getDelFlag, 0).eq(SysOrgDepartment::getOrgId, LabReqMain::getOrgId).isNotNull(SysOrgDepartment::getCode));
        lambdaQueryWrapper.eq(LabReqMain::getDelFlag, 0);
        if (ToolsUtils.isNotEmpty(labReqMain.getStartTime())) {
            Timestamp startTime = Timestamp.valueOf(labReqMain.getStartTime());
            //申请时间
            lambdaQueryWrapper.ge(LabReqMain::getReqTime, startTime);
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getEndTime())) {
            Timestamp endTime = Timestamp.valueOf(labReqMain.getEndTime());
            lambdaQueryWrapper.le(LabReqMain::getReqTime, endTime);
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getReqNo())) {
            lambdaQueryWrapper.eq(LabReqMain::getReqNo, labReqMain.getReqNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getBedNo())) {
            lambdaQueryWrapper.eq(LabReqMain::getBedNo, labReqMain.getBedNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatNo())) {
            lambdaQueryWrapper.eq(LabReqMain::getPatNo, labReqMain.getPatNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatNa())) {
            lambdaQueryWrapper.like(LabReqMain::getPatNa, labReqMain.getPatNa());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getIdNo())) {
            lambdaQueryWrapper.eq(LabReqMain::getIdNo, labReqMain.getIdNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getTelNo())) {
            lambdaQueryWrapper.like(LabReqMain::getTelNo, labReqMain.getTelNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getTestPurpose())) {
            lambdaQueryWrapper.like(LabReqMain::getTestPurpose, labReqMain.getTestPurpose());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getReqDept())) {
            lambdaQueryWrapper.eq(LabReqMain::getReqDept, labReqMain.getReqDept());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatType())) {
            lambdaQueryWrapper.eq(LabReqMain::getPatType, labReqMain.getPatType());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getCompanyCode())) {
            lambdaQueryWrapper.eq(LabReqMain::getInspectCompany, labReqMain.getCompanyCode());
        }
        List<LabReqMain> list = labReqMainMapper.selectList(lambdaQueryWrapper);

        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        for (LabReqMain reqMain : list) {
            if (StringUtils.isNotBlank(reqMain.getPatType()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(reqMain.getPatType())).findFirst().ifPresent(stringObjectMap -> reqMain.setPatTypeNa((String) stringObjectMap.get("name")));
            }
        }

        return Result.succ(1, "查询成功", list);
    }

    /*调用接口返回申请信息*/
    public Result getApiReqMainInfo(AddLabMaininfo labReqMain) {
        /*调接口*/
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        String orgId = RedisUserManager.getStoreOrg("currentOrg" + token);
        SysUser sysUser = RedisUserManager.getUser();
        LabReqMain q = new LabReqMain();
        q.setReqNo(labReqMain.getReqNo());
        q.setOrgId(orgId);
        q.setUsername(sysUser.getUsername());
        q.setRealname(sysUser.getRealname());

        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());//

        try {
            if (CollectionUtils.isNotEmpty(collect)) {
                for (String webUrl : collect) {
                    String returnMsg = HttpUtil.createPost(webUrl + "/public/SyncReqMain").body(JSONUtil.toJsonStr(q)).contentType("application/json").execute().sync().body();
                    JSONObject jsonObject = new JSONObject(returnMsg);
                    JSONObject status = jsonObject.getJSONObject("status");
                    String code = status.get("code").toString();
                    if ("400".equals(code)) {
                        return Result.fail(jsonObject.getStr("data"));
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("接口管理平台异常,请检查");
        }
        return Result.succ(200, "有数据，同步成功", null);
    }

    /**
     * 通过id获取关联的部门和数据字典信息
     *
     * @param id
     * @return
     */
    public LabMaininfo getMainInfoById(String id) {
        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabMaininfo.class);
        queryWrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);
        queryWrapper.selectAs(SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
        queryWrapper.selectAs("req", PubEmployee::getName, LabMaininfo::getReqDoctorNa);
        queryWrapper.selectAs("test", SysUser::getRealname, LabMaininfo::getTestDoctorNa);
        queryWrapper.selectAs("chk", SysUser::getRealname, LabMaininfo::getChkDoctorNa);
        queryWrapper.selectAs("rechk", SysUser::getRealname, LabMaininfo::getReChkDoctorNa);
        queryWrapper.selectAs("prt", SysUser::getRealname, LabMaininfo::getPrintDoctorNa);
        queryWrapper.selectAs("sampl", SysUser::getRealname, LabMaininfo::getSamplingDoctorNa);
        queryWrapper.selectAs("signer", SysUser::getRealname, LabMaininfo::getSignerDoctorNa);
        queryWrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
        queryWrapper.leftJoin(LabSampleType.class, LabSampleType::getSampleTypeCode, LabMaininfo::getSampleType);
        queryWrapper.leftJoin(SysOrgDepartment.class, SysOrgDepartment::getCode, LabMaininfo::getReqDept);
        queryWrapper.leftJoin(PubEmployee.class, "req", p -> p.eq(PubEmployee::getCode, LabMaininfo::getReqDoctor).eq(PubEmployee::getDelFlag, 0));
        queryWrapper.leftJoin(SysUser.class, "test", SysUser::getUsername, LabMaininfo::getTestDoctor);
        queryWrapper.leftJoin(SysUser.class, "chk", SysUser::getUsername, LabMaininfo::getChkDoctor);
        queryWrapper.leftJoin(SysUser.class, "rechk", SysUser::getUsername, LabMaininfo::getReChkDoctor);
        queryWrapper.leftJoin(SysUser.class, "prt", SysUser::getUsername, LabMaininfo::getPrintDoctor);
        queryWrapper.leftJoin(SysUser.class, "sampl", SysUser::getUsername, LabMaininfo::getSamplingDoctor);
        queryWrapper.leftJoin(SysUser.class, "signer", SysUser::getUsername, LabMaininfo::getSignerDoctor);
        queryWrapper.leftJoin(LabRptGroup.class, "rptgrp", LabRptGroup::getRptGroup, LabMaininfo::getRptGroup);
        queryWrapper.eq(LabMaininfo::getId, id);

        queryWrapper.orderByAsc(LabMaininfo::getSampleNo);
        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);

        // 获取数据字典(病人类型、性别、证件类型)
        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();
        for (LabMaininfo maininfo : labMaininfos) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));
            }
        }
        if (CollectionUtils.isNotEmpty(labMaininfos)) {
            return labMaininfos.get(0);
        } else {
            return new LabMaininfo();
        }
    }

    private List<String> getListValueMethod(String value) {
        // 去掉首尾的方括号
        String str = value.replaceAll("\\[|\\]", "");
        // 分割字符串
        String[] parts = str.split(",");
        // 创建一个列表来存储整数
        List<String> list = new ArrayList<>();
        // 遍历分割后的字符串数组，并将其转换为整数后添加到列表中
        for (String part : parts) {
            // 去掉引号
            String numStr = part.trim().replaceAll("\"", "");
            list.add(numStr);
        }
        return list;
    }

    public static int differentDaysByMillisecond(Date date1, Date date2) {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
        return days;
    }

    /**
     * Timestamp -> Date
     *
     * @param timestamp 时间戳
     * @return
     * @author whx
     * @date
     */
    public Date timeToDate(Timestamp timestamp) {

        // Timestamp -> String
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(timestamp);

        // String -> Date
        Date date = new Date();
        // 注意format的格式要与日期String的格式相匹配
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date = sdf.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
